package com.yituo.mjworld.mvc.service;

import com.alibaba.fastjson.JSONObject;
import com.yituo.mjworld.core.utils.BaseDao;
import com.yituo.mjworld.core.web.core.BaseForm;
import com.yituo.mjworld.core.web.core.Result;
import com.yituo.mjworld.mvc.form.DeleteForm;
import com.yituo.mjworld.mvc.form.QueryForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xq
 */
@Service
public abstract class BaseService {

  private static final String PARAM_QUERY_STR_ALL = "all";
  @Autowired
  protected BaseDao baseDao;

  /**
   * 获取清单
   *
   * @param form 查询表单
   * @return
   */
  public abstract JSONObject getList(QueryForm form);

  /**
   * 删除某项
   *
   * @param form 删除表单
   * @return
   */
  public abstract Result delete(DeleteForm form);

  /**
   * 保存与更新
   *
   * @param baseForm 更新表单
   * @return
   */
  public abstract Result saveOrUpdate(BaseForm baseForm) throws InvocationTargetException, IllegalAccessException;

  /**
   * 通用的分页查询方法.
   * <p>
   * 禁止重载该方法
   *
   * @return
   */
  public final JSONObject get(String sql, String countSql, QueryForm form, Map<String, Object> params) {
    JSONObject result = new JSONObject();
    long total = 0;
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    result.put("rows", list);
    result.put("total", total);
    total = this.baseDao.countBySql(countSql, params);
    if (total == 0) {
      return result;
    }
    list = this.baseDao.findByPageForMap(sql, form.page, form.rows, params);
    result.put("rows", list);
    result.put("total", total);
    return result;
  }


}
